package com.hospitalsystem.service.impl;

import com.hospitalsystem.dao.ArrangeDao;
import com.hospitalsystem.dao.PatientDao;
import com.hospitalsystem.entity.*;
import com.hospitalsystem.service.PatientService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * (Patient)表服务实现类
 *
 * @author makejava
 * @since 2024-12-28 19:32:59
 */
@Service("patientService")
public class PatientServiceImpl implements PatientService {
    @Resource
            private PatientDao patientDao;
    @Resource
            private ArrangeDao arrangeDao;

    int numPerHour = 15;
    String theTime = "2024-12-31 00:00:00";

    /**
     * 通过ID查询单条数据
     *
     * @param  pId
     * @return 实例对象
     */
    @Override
    public Patient queryById(String pId) {
        return this.patientDao.queryById(pId);
    }

    /**
     * 分页查询
     *
     * @param patient 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<Patient> queryByPage(Patient patient, PageRequest pageRequest) {
        long total = this.patientDao.count(patient);
        return new PageImpl<>(this.patientDao.queryAllByLimit(patient, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param patient 实例对象
     * @return 实例对象
     */
    @Override
    public Patient insert(Patient patient) {
        this.patientDao.insert(patient);
        return patient;
    }

    /**
     * 修改数据
     *
     * @param patient 实例对象
     * @return 实例对象
     */
    @Override
    public Patient update(Patient patient) {
        this.patientDao.update(patient);
        return this.queryById(patient.getPId());
    }

    /**
     * 通过主键删除数据
     *
     * @param  pId
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String pId) {
        return this.patientDao.deleteById(pId) > 0;
    }

    @Override
    public Patient add(String id){
        this.patientDao.add(id);
        return(this.queryById(id));
    }

    @Override
    public State login(String id, String password){

        Integer num = this.patientDao.checkId(id);
        if(num.equals(0)){
            return new State("0");
        }
        Patient patient = this.patientDao.getPassword(id);
        if(password.equals(patient.getPassword())){
            return new State("2",patient);
        }
        else{
            return new State("1");
        }

    }

    @Override
    public List<String> getDepartment(){
        return this.patientDao.getDepartment();
    }

    @Override
    public Map<String,Integer> getDoctorByDepartment(String department,String time){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Doctor> doctors = new ArrayList<>();
        Map<String,Integer> restTable = new HashMap<>();

        try{
            //解析时间串
            Date date = sdf.parse(time);
            //使用calendar处理日期时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);

            //将秒和毫秒设置为0
            calendar.set(Calendar.SECOND,0);
            calendar.set(Calendar.MINUTE,0);

            //格式化回字符串
            String start = sdf.format(calendar.getTime());

            //将秒和毫秒设置为59
            calendar.set(Calendar.SECOND,59);
            calendar.set(Calendar.MINUTE,59);

            //格式化回字符串
            String end = sdf.format(calendar.getTime());

            System.out.println("the codeed time:  " + start);
            System.out.println("the codeed time:  " + end);

            doctors = this.patientDao.getDoctorByDepartment(department);

            for(Doctor doctor : doctors){
                int restNum = numPerHour - this.patientDao.getDoctorNumByTime(doctor.getDId(),start,end);
                restTable.put(doctor.getName(),restNum);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return restTable;
    }

    @Override
    public Arrange addArrange(String pId, String dId, String time){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String arrange_id="01234";
        try{
            //生成本地时间
            Date date = new Date();

            //接卸生成起点时间
            Date start = sdf.parse(theTime);

            //生成基于起点时间的时间戳
            long timestamp = (date.getTime() - start.getTime()) / 10;

            //截取时间戳前五位
            arrange_id = "ARR" + String.valueOf(timestamp).substring(0, 5);
        }catch (Exception e){
            e.printStackTrace();
        }

        this.patientDao.addArrange(arrange_id,pId,dId,time);
        return this.arrangeDao.queryById(arrange_id);
    }

//    @Override
//    public State chargeForArrange(String arrangeId){
//
//        this.chargeForArrange(arrangeId);
//        return new State("缴费成功");
//    }

    @Override
    public List<Map<String,Object>> getQueue(String did){
      List<Map<String,Object>> patients = new ArrayList<>();

      //生成当前时间
      Date now = new Date();

      List<Arrange> arranges = this.patientDao.getArrange(did);

      Comparator<Arrange> comparator = new ArrangeComparator();
      arranges.sort(comparator);

      for(Arrange arrange:arranges){
            Patient p = this.patientDao.getPassword(arrange.getPId());
            Map<String,Object> tmp = p.converToMap();
            String birth = p.getBirthday();
            String idCard = p.getIdCard();
          DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
          LocalDate birthday = LocalDate.parse(birth,formatter);
          //获取当前日期
          LocalDate today = LocalDate.now();

          //计算年龄
          Period period = Period.between(birthday,today);
          int age = period.getYears();

          tmp.put("age",age);
          tmp.put("arrangeTime",arrange.getArrangeTime());
          tmp.put("arrangeid",arrange.getArrangeId());
          tmp.put("idCard", idCard);
          patients.add(tmp);
      }

      return patients;
    };
}
